import csv
import json
from datetime import datetime

input_file = r'data-analysis\海塘新班子电量分析\mqtt_messages.log'
output_csv = r'data-analysis\海塘新班子电量分析\soc_data.csv'
target_string = 'GL-6-A001F31'

try:
    with open(input_file, 'r', encoding='utf-8') as f:
        # 提取包含目标字符串的JSON数据行
        matching_lines = [line for line in f if target_string in line]
        
    # 解析数据并提取字段
    data_records = []
    for line in matching_lines:
        try:
            json_data = json.loads(line.split("Message: ")[1])  # 从消息体提取JSON
            upload_time = json_data["data"]["Upload_time"]
            soc = json_data["data"]["soc"]
            # 将时间字符串转为datetime对象（用于后续排序和绘图）
            time_obj = datetime.strptime(upload_time, "%Y-%m-%d %H:%M:%S")
            data_records.append([time_obj, soc])
        except (IndexError, KeyError, json.JSONDecodeError) as e:
            print(f"解析错误: {str(e)}，跳过该行")

    # 按时间排序数据
    data_records.sort(key=lambda x: x[0])

    # 写入CSV文件
    with open(output_csv, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(["Upload_time", "soc"])  # 写入表头
        writer.writerows(data_records)
        print(f"成功保存{len(data_records)}条记录到 {output_csv}")

except FileNotFoundError:
    print(f"错误：文件 '{input_file}' 未找到")
except Exception as e:
    print(f"处理时发生错误: {str(e)}")

#------------------------------------------------------------------------------    
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 修复中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 读取CSV并转换时间格式
df = pd.read_csv(output_csv, parse_dates=['Upload_time'])
df.set_index('Upload_time', inplace=True)  # 设置时间为索引

# 创建画布
plt.figure(figsize=(14, 7))
plt.plot(df.index, df['soc'], marker='o', linestyle='-', color='#2c7fb8', markersize=6)

# 美化图表
plt.title('设备电量随时间变化趋势\n(GL-6-A00FACE)', fontsize=14, pad=20)
plt.xlabel('时间', fontsize=12)
plt.ylabel('剩余电量 (%)', fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
# 时间轴密度控制
ax = plt.gca()
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax.xaxis.set_minor_locator(mdates.MinuteLocator(interval=15))
plt.xticks(rotation=30, ha='right')  # 适度旋转+右对齐[4](@ref)

# 添加数据标签
for index, (time, soc) in enumerate(zip(df.index, df['soc'])):
    if index % (len(df)//10 + 1) == 0:  # 动态间隔标注
        plt.text(time, soc+0.8, f'{soc}%', ha='center', fontsize=9, color='#2c7fb8')
        
# 自动调整布局并保存图片
plt.tight_layout()
plt.savefig(r'data-analysis\海塘新班子电量分析\soc_trend.png', dpi=300)
plt.show()